package org.tobuy.servlet;

import java.io.IOException;
import java.sql.Date;
import java.sql.Timestamp;

import org.tobuy.factory.*;
import org.tobuy.vo.*;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DirectBuy extends HttpServlet {

	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String path = "buyResult.jsp";
		String info = new String();
		String item_id = req.getParameter("item_id");
		
		Item item = new Item();
		try {
			item = ItemDAOFactory.getIItemDAOInstance().findItem(item_id);
			System.out.println(item.getItem_name());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		HttpSession session = req.getSession();
		User buyer = (User)session.getAttribute("user");
		if(buyer==null){
			info = "Please login first in order to buy stuff!";
		}else{
			Deal deal = new Deal();
			deal.setBuyer_id(buyer.getUser_id());
			deal.setSeller_id(item.getSeller_id());
			deal.setItem_id(Integer.parseInt(item_id));
			deal.setDeal_price(item.getPrice());
			deal.setDeal_date(new Timestamp(System.currentTimeMillis()));
			
			try {
				if(DealDAOFactory.getIDealDAOInstance().addDeal(deal)){
					info="You just brought it successfully!";
				}else{
					info="Sorry, failed to buy stuff, please try again later!";
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		req.setAttribute("info", info);
		req.getRequestDispatcher(path).forward(req, resp);

		

	
	}


	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);

	
	}

}
